package com.ymt.bpm.web.rest.platform.biz;

import com.alibaba.fastjson.JSONObject;
import com.ymt.bpm.service.platform.biz.BizDataService;
import com.ymt.bpm.util.Const;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/platform/biz/data")
public class BizDataResource {

    /**
     * Logger
     */
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BizDataService bds;

    @PostMapping("/query")
    public JSONObject queryDhx(HttpServletRequest req,
                            @RequestParam(value = "appId", required = false)String appId,
                            @RequestParam("fromRow")int frowRow,
                            @RequestParam("toRow")int toRow,
                            @RequestParam("model")String model,
                            @RequestParam("cols")String cols,
                            @RequestParam("ordercolumns")String ordercolumns,
                            @RequestParam("timezoneOffset")int timezoneOffset,
                            @RequestParam(value = "searchkey", required = false)String searchkey,
                            @RequestParam(value = "conditions", required = false)String conditions
                            ) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String lang = userDetail.get(Const.LANG);
        if (log.isDebugEnabled()) {
            log.debug("queryDhx tenantId="+tenantId);
            log.debug("queryDhx appId="+appId);
            log.debug("queryDhx fromRow="+frowRow);
            log.debug("queryDhx toRow="+toRow);
            log.debug("queryDhx model="+model);
            log.debug("queryDhx cols="+cols);
            log.debug("queryDhx ordercolumns="+ordercolumns);
            log.debug("queryDhx timezoneOffset="+timezoneOffset);
            log.debug("queryDhx searchkey="+searchkey);
            log.debug("queryDhx conditions="+conditions);
        }
        return bds.queryDhx(tenantId, appId, frowRow, toRow, model, cols, ordercolumns, lang, timezoneOffset, searchkey, conditions);
    }

    @GetMapping("/{sharedId}")
    public JSONObject get(HttpServletRequest req,
                          @PathVariable("sharedId")String sharedId,
                          @RequestParam("models")String models,
                          @RequestParam(value = "appId", required = false)String appId,
                          @RequestParam("timezoneOffset")int timezoneOffset) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        if (log.isDebugEnabled()) {
            log.debug("get sharedId="+sharedId);
            log.debug("get tenantId="+tenantId);
            log.debug("get appId="+appId);
            log.debug("get models="+models);
            log.debug("get timezoneOffset="+timezoneOffset);
        }
        return bds.get(tenantId, appId, models, sharedId, timezoneOffset);
    }

    @PostMapping("/save")
    public JSONObject save(HttpServletRequest req,
                           @RequestParam("tsId")String sharedId,
                           @RequestParam("data")String data,
                           @RequestParam(value = "appId", required = false)String appId) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String loginName = userDetail.get(Const.LOGINNAME);
        String displayName = userDetail.get(Const.DISPLAYNAME);
        if (log.isDebugEnabled()) {
            log.debug("save sharedId="+sharedId);
            log.debug("save tenantId="+tenantId);
            log.debug("save appId="+appId);
            log.debug("save data="+data);
            log.debug("save loginName="+loginName);
            log.debug("save displayName="+displayName);
        }
        return bds.save(tenantId, appId, data, sharedId, loginName, displayName);
    }

    @PostMapping("/delete")
    public JSONObject delete(HttpServletRequest req,
                           @RequestParam("sharedIds")String sharedIds,
                           @RequestParam("models0")String models0,
                           @RequestParam("models1")String models1,
                           @RequestParam(value = "appId", required = false)String appId) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String loginName = userDetail.get(Const.LOGINNAME);
        String displayName = userDetail.get(Const.DISPLAYNAME);
        if (log.isDebugEnabled()) {
            log.debug("delete sharedIds="+sharedIds);
            log.debug("delete tenantId="+tenantId);
            log.debug("delete appId="+appId);
            log.debug("delete models0="+models0);
            log.debug("delete models1="+models1);
        }
        return bds.delete(tenantId, appId, models0, models1, sharedIds, loginName, displayName);
    }

    @PostMapping("/querySubAllDhx")
    public JSONObject querySubAllDhx(HttpServletRequest req,
                           @RequestParam("piId")String sharedId,
                           @RequestParam("param")String param,
                           @RequestParam(value = "appId", required = false)String appId) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String loginName = userDetail.get(Const.LOGINNAME);
        String displayName = userDetail.get(Const.DISPLAYNAME);
        if (log.isDebugEnabled()) {
            log.debug("querySubAllDhx sharedId="+sharedId);
            log.debug("querySubAllDhx tenantId="+tenantId);
            log.debug("querySubAllDhx appId="+appId);
            log.debug("querySubAllDhx param="+param);
            log.debug("querySubAllDhx loginName="+loginName);
            log.debug("querySubAllDhx displayName="+displayName);
        }
        return bds.querySubAllDhx(tenantId, appId, param, sharedId);
    }

    @PostMapping("/saveSubAllDhx")
    public JSONObject saveSubAllDhx(HttpServletRequest req,
                                     @RequestParam("piId")String sharedId,
                                     @RequestParam("param")String param,
                                     @RequestParam(value = "appId", required = false)String appId) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String loginName = userDetail.get(Const.LOGINNAME);
        String displayName = userDetail.get(Const.DISPLAYNAME);
        if (log.isDebugEnabled()) {
            log.debug("saveSubAllDhx sharedId="+sharedId);
            log.debug("saveSubAllDhx tenantId="+tenantId);
            log.debug("saveSubAllDhx appId="+appId);
            log.debug("saveSubAllDhx param="+param);
            log.debug("saveSubAllDhx loginName="+loginName);
            log.debug("saveSubAllDhx displayName="+displayName);
        }
        return bds.saveSubAllDhx(tenantId, appId, param, sharedId);
    }

    @PostMapping(value = "/getImportTemplate", produces = "application/ms-excel")
    public void getImportTemplate(HttpServletRequest request,
                                  HttpServletResponse response,
                                  String colsStr) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String lang = userDetail.get(Const.LANG);

    }

    private void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
        final String userAgent = request.getHeader("USER-AGENT");
        try {
            String finalFileName = null;
            if(StringUtils.contains(userAgent, "MSIE")){//IE浏览器
                finalFileName = URLEncoder.encode(fileName,"UTF8");
            }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
                finalFileName = new String(fileName.getBytes(), "ISO8859-1");
            }else{
                finalFileName = URLEncoder.encode(fileName,"UTF8");//其他浏览器
            }
            response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");//这里设置一下让浏览器弹出下载提示框，而不是直接在浏览器中打开
        } catch (UnsupportedEncodingException e) {
        }
    }

}
